package com.centaline.androidsalesblog.widgets;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.centaline.androidsalesblog.R;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * 语音对话框
 * Created by guilin on 16/2/19.
 */
public class SpeechDialog extends AlertDialog {

    private final SpeechRecognizer speechRecognizer;
    private final SpeechResult speechResult;
    private AppCompatTextView atv_dialog_tips, atv_dialog_retry;
    private FloatingActionButton fab_voice;
    private ImageView img_speech;

    private String dialog_tips1, dialog_tips2;

    private StringBuilder result = new StringBuilder();

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setSpeechTips(false);
            setVoiceButtonEnable(false);
            setRetryVisibility(false);
            startListening();
        }
    };

    private RecognizerListener recognizerListener = new RecognizerListener() {
        @Override
        public void onVolumeChanged(int i, byte[] bytes) {
            scaleView(i);
        }

        @Override
        public void onBeginOfSpeech() {
            result.setLength(0);
            setVoiceButtonEnable(false);
        }

        @Override
        public void onEndOfSpeech() {

        }

        @Override
        public void onResult(RecognizerResult recognizerResult, boolean isLast) {
            final String text = parse(recognizerResult);
            result.append(text);
            if (isLast) {
                cancel();
                speechResult.result(result.toString());
            }
        }

        @Override
        public void onError(SpeechError speechError) {
            setSpeechTips(true);
            setVoiceButtonEnable(true);
            setRetryVisibility(true);
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };

    public SpeechDialog(Context context, SpeechRecognizer speechRecognizer, SpeechResult speechResult) {
        super(context);
        this.speechRecognizer = speechRecognizer;
        this.speechResult = speechResult;

        View view = LayoutInflater.from(context).inflate(R.layout.speech_dialog, null);
        atv_dialog_tips = (AppCompatTextView) view.findViewById(R.id.atv_dialog_tips);
        atv_dialog_retry = (AppCompatTextView) view.findViewById(R.id.atv_dialog_retry);
        fab_voice = (FloatingActionButton) view.findViewById(R.id.fab_voice);
        fab_voice.setOnClickListener(mOnClickListener);
        img_speech = (ImageView) view.findViewById(R.id.img_speech);

        dialog_tips1 = getContext().getString(R.string.speech_dialog_tips1);
        dialog_tips2 = getContext().getString(R.string.speech_dialog_tips2);

        setVoiceButtonEnable(false);
        setSpeechTips(false);
        setView(view);
    }

    @Override
    public void show() {
        super.show();
        startListening();
    }

    /**
     * 开始说话
     */
    private void startListening() {
        setSpeechTips(false);
        speechRecognizer.startListening(recognizerListener);
    }

    private void scaleView(int volume) {
        final float scale = 1f + volume / 30f;
        img_speech.setScaleX(scale);
        img_speech.setScaleY(scale);
    }

    /**
     * 设置语音按钮
     */
    private void setVoiceButtonEnable(boolean enable) {
        fab_voice.setEnabled(enable);
    }

    /**
     * 设置提示
     */
    private void setSpeechTips(boolean retry) {
        atv_dialog_tips.setText(retry ? dialog_tips2 : dialog_tips1);
    }

    /**
     * 设置重试提示
     */
    private void setRetryVisibility(boolean visibility) {
        atv_dialog_retry.setVisibility(visibility ? View.VISIBLE : View.INVISIBLE);
    }

    /**
     * 解析
     */
    private String parse(RecognizerResult recognizerResult) {
        final StringBuilder sb = new StringBuilder();
        try {
            JSONTokener jsonTokener = new JSONTokener(recognizerResult.getResultString());
            JSONObject jsonObject = new JSONObject(jsonTokener);
            JSONArray jsonArray = jsonObject.getJSONArray("ws");
            final int length = jsonArray.length();
            for (int i = 0; i < length; i++) {
                JSONArray items = jsonArray.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                sb.append(obj.getString("w"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return "";
        }
        return sb.toString();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (speechRecognizer.isListening())
            speechRecognizer.stopListening();
    }

    /**
     * 语音结果监听
     */
    public interface SpeechResult {
        void result(String result);
    }
}
